//
//  XDLMRegisterNowViewController.m
//  xindailianmeng
//
//  Created by 许佳奇 on 17/2/15.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//********注册页面

#import "XDLMRegisterNowViewController.h"
#import "XDLMLoginViewController.h"
#import "XDLMUIFactory.h"
#import "AFHTTPSessionManager+POST.h"
#import "ZHRTBasicMethod.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"

#import "XDLMRegisteViewController.h"

#define TCOLOR [UIColor colorWithRed:187.0/255.0 green:147.0/255.0 blue:115.0/255.0 alpha:1]
@interface XDLMRegisterNowViewController ()<UITextFieldDelegate>

@end

@implementation XDLMRegisterNowViewController

{
    UIView *_backView;//背景view
    UITextField *_PhoneNumTF;
    UIButton *_NextBtn;//下一步按钮
    NSString *previousTextFieldContent;
    UITextRange *previousSelection;
    
    UITextField *_tuiTF;//推荐码field
    UILabel *_TSLab;//提示lab
    UIImageView *_TSImgView;//
    BOOL _isRegister;//是否注册
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _backView = [[UIView alloc] initWithFrame:kScreenB];
    _backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backView];
    
    
    self.navigationItem.title = @"输入手机号";
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    UIFont *font = [UIFont fontWithName:@"Arial-ItalicMT" size:20];
    NSDictionary *dic = @{NSFontAttributeName:font,
                          NSForegroundColorAttributeName: TCOLOR};
    self.navigationController.navigationBar.titleTextAttributes =dic;
    self.view.backgroundColor = [UIColor blackColor];
    [self addviews];
    //    [self loadData];
    // Do any additional setup after loading the view.
}
- (void)addviews
{
    UIImage *backIma = [UIImage imageNamed:@"login_bg"];
    UIImageView *backImgView = [[UIImageView alloc] initWithImage:backIma];
    backImgView.frame = kScreenB;
    backImgView.userInteractionEnabled = YES;
    [_backView addSubview:backImgView];
    
    _PhoneNumTF = [[UITextField alloc] initWithFrame:CGRectMake(54, 113*kscale, kScreenW - 108, 40*kscale)];
    _PhoneNumTF.placeholder = @"请输入手机号登录或注册";
    _PhoneNumTF.textColor = TCOLOR;
    _PhoneNumTF.font = [UIFont systemFontOfSize:20];
    _PhoneNumTF.delegate = self;
    _PhoneNumTF.clearButtonMode = UITextFieldViewModeAlways;
    _PhoneNumTF.keyboardType = UIKeyboardTypeNumberPad;
//    _PhoneNumTF.clearsOnBeginEditing = YES;
    
    //改变clearbutton背景图片
    UIButton *clearButton = [_PhoneNumTF valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"clearbtn"] forState:UIControlStateNormal];
    
    //设置placeholder的字体和颜色
    [_PhoneNumTF setValue:TCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_PhoneNumTF setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [_PhoneNumTF addTarget:self action:@selector(numberChange:) forControlEvents:UIControlEventEditingChanged];
    [backImgView addSubview:_PhoneNumTF];
    
    UILabel *lineLab = [[UILabel alloc] initWithFrame:CGRectMake(54, 153*kscale, kScreenW - 108, 1)];
    lineLab.backgroundColor = TCOLOR;
    [backImgView addSubview:lineLab];
    
    if (!_isRegister) {
        _tuiTF = [[UITextField alloc] initWithFrame:CGRectMake(54, 163*kscale, kScreenW - 108, 40*kscale)];
        _tuiTF.placeholder = @"请输入正确推荐码（选填）";
        _tuiTF.textColor = TCOLOR;
        _tuiTF.font = [UIFont systemFontOfSize:22];
        //    _tuiTF.delegate = self;
        _tuiTF.clearButtonMode = UITextFieldViewModeAlways;
        //    _tuiTF.keyboardType = UIKeyboardTypeNumberPad;
        _tuiTF.clearsOnBeginEditing = YES;
        
        //改变clearbutton背景图片
        UIButton *clearButtonTwo = [_tuiTF valueForKey:@"_clearButton"];
        [clearButtonTwo setImage:[UIImage imageNamed:@"clearbtn"] forState:UIControlStateNormal];
        
        //设置placeholder的字体和颜色
        [_tuiTF setValue:TCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [_tuiTF setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
        //    [_tuiTF addTarget:self action:@selector(numberChange:) forControlEvents:UIControlEventEditingChanged];
        [backImgView addSubview:_tuiTF];
        
        UILabel *lineLabTwo = [[UILabel alloc] initWithFrame:CGRectMake(54, 203*kscale, kScreenW - 108, 1)];
        lineLabTwo.backgroundColor = TCOLOR;
        [backImgView addSubview:lineLabTwo];
        

    } else {
        
        [_tuiTF removeFromSuperview];
    }
    
    CGFloat nextBtnY = _tuiTF ? CGRectGetMaxY(_tuiTF.frame) + 20 :  CGRectGetMaxY(_PhoneNumTF.frame) + 20;
        //下一步按钮
    _NextBtn = [[UIButton alloc] initWithFrame:CGRectMake(54, nextBtnY, kScreenW - 108, 50*kscale)];
    [_NextBtn setBackgroundImage:[UIImage imageNamed:@"nextone"] forState:UIControlStateNormal];
    [_NextBtn addTarget:self action:@selector(NextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    //    _NextBtn.userInteractionEnabled = NO;
    [backImgView addSubview:_NextBtn];
    
    UIView *dowmView = [[UIView alloc] initWithFrame:CGRectMake(65*kscale, 300*kscale, kScreenW - 130, 16)];
    [backImgView addSubview:dowmView];
    UIImage *zhengque = [UIImage imageNamed:@"agree_yes"];
    UIImageView *zhengImgView = [[UIImageView alloc] initWithImage:zhengque];
    zhengImgView.frame = CGRectMake(0, 2, 12, 12);
    [dowmView addSubview:zhengImgView];
    
    UILabel *alreadyReadLab = [[UILabel alloc] initWithFrame:CGRectMake(16*kscale, 0, 90*kscale, 12)];
    alreadyReadLab.text = @"我已阅读并同意";
    alreadyReadLab.adjustsFontSizeToFitWidth = YES;
    alreadyReadLab.textColor = [UIColor grayColor];
    [dowmView addSubview:alreadyReadLab];
    
    UIButton *xindaiBtn = [[UIButton alloc] initWithFrame:CGRectMake(98*kscale, 2, 150*kscale, 12)];
    xindaiBtn.titleLabel.font = [UIFont systemFontOfSize:FONTSIZE12];
    [xindaiBtn setTitle:@"《新贷联盟用户注册协议》" forState:UIControlStateNormal];
    [xindaiBtn setTitleColor:TCOLOR forState:UIControlStateNormal];
    [dowmView addSubview:xindaiBtn];
    
    UILabel *goalLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenH - 150*kscale, kScreenW, 60)];
    goalLab.textColor = TCOLOR;
    goalLab.text = @"定一个小目标，先赚他一个亿";
    goalLab.font = [UIFont systemFontOfSize:FONTSIZE18];
    goalLab.textAlignment = NSTextAlignmentCenter;
    [_backView addSubview:goalLab];
}
//请求数据
- (void)loadData
{
    NSString *text = [_PhoneNumTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSDictionary *param = @{@"method":@"getMobileCode",@"mobile":text};
        [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject)
     {
         if ([responseObject[@"code"] isEqualToString:@"100000"])
         {
             NSLog(@"%@",responseObject);
             XDLMRegisteViewController *registerCtr = [[XDLMRegisteViewController alloc] init];
             registerCtr.phoneNumber = _PhoneNumTF.text;
             registerCtr.textCode = _tuiTF.text;
             [self.navigationController pushViewController:registerCtr animated:YES];
         }
         
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         
     }];

    
}
#pragma mark -- 点击方法
//点击下一步按钮
- (void)NextBtnClick
{
   
    
        [self loadData];
}
//监听输入框值变化
- (void)numberChange:(UITextField *)textField
{
    //限制手机账号长度（有两个空格）
    if (textField.text.length > 13) {
        textField.text = [textField.text substringToIndex:13];
    }
    
    NSUInteger targetCursorPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
    
    NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *preStr = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //正在执行删除操作时为0，否则为1
    char editFlag = 0;
    if (currentStr.length <= preStr.length) {
        editFlag = 0;
    }
    else {
        editFlag = 1;
    }
    
    NSMutableString *tempStr = [NSMutableString new];
    
    int spaceCount = 0;
    if (currentStr.length < 3 && currentStr.length > -1) {
        spaceCount = 0;
    }else if (currentStr.length < 7 && currentStr.length > 2) {
        spaceCount = 1;
    }else if (currentStr.length < 12 && currentStr.length > 6) {
        spaceCount = 2;
    }
    
    for (int i = 0; i < spaceCount; i++) {
        if (i == 0) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(0, 3)], @" "];
        }else if (i == 1) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(3, 4)], @" "];
        }else if (i == 2) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
        }
    }
    
    if (currentStr.length == 11) {
        [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
    }
    if (currentStr.length < 4) {
        [tempStr appendString:[currentStr substringWithRange:NSMakeRange(currentStr.length - currentStr.length % 3, currentStr.length % 3)]];
    }else if(currentStr.length > 3 && currentStr.length <12) {
        NSString *str = [currentStr substringFromIndex:3];
        [tempStr appendString:[str substringWithRange:NSMakeRange(str.length - str.length % 4, str.length % 4)]];
        if (currentStr.length == 11) {
            [tempStr deleteCharactersInRange:NSMakeRange(13, 1)];
        }
    }
    textField.text = tempStr;
    // 当前光标的偏移位置
    NSUInteger curTargetCursorPosition = targetCursorPosition;
    
    if (editFlag == 0) {
        //删除
        if (targetCursorPosition == 9 || targetCursorPosition == 4) {
            curTargetCursorPosition = targetCursorPosition - 1;
        }
    }else {
        //添加
        if (currentStr.length == 8 || currentStr.length == 4) {
            curTargetCursorPosition = targetCursorPosition + 1;
        }
    }
    UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];
    [textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition :targetPosition]];
    
    //判断是否是手机号码
    _TSLab.hidden = YES;
    _TSImgView.hidden = YES;
    NSString * phone =  [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([ZHRTBasicMethod isMobileNumber:phone]) {
        [_NextBtn setBackgroundImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
        _NextBtn.userInteractionEnabled = YES;
        
        
    }
    else
    {
        [_NextBtn setBackgroundImage:[UIImage imageNamed:@"nextone"] forState:UIControlStateNormal];
        //        _NextBtn.userInteractionEnabled = NO;
        if (phone.length == 11) {
            _TSImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gantan"]];
            _TSImgView.frame = CGRectMake(52, 215*kscale, 15, 15);
            _TSImgView.hidden = NO;
            [_backView addSubview:_TSImgView];
            _TSLab = [[UILabel alloc] initWithFrame:CGRectMake(72, 215*kscale, 200, 15)];
            _TSLab.text = @"请输入正确手机号";
            _TSLab.font = [UIFont systemFontOfSize:14];
            _TSLab.textColor = [UIColor grayColor];
            _TSLab.hidden = NO;
            [_backView addSubview:_TSLab];
        }
    }
}
#pragma mark -- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;
    
    return YES;
}
#pragma mark -- 辅助方法
//点击空白区域，隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //结束编辑
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
